from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from django import http
import logging
import random

from meiduo_mall.libs.captcha.captcha import captcha
# from meiduo_mall.libs.yuntongxun.ccp_sms import CCP
from celery_tasks.sms.tasks import send_sms_code

# Create your views here.

# 创建日志生成器
logger = logging.getLogger('django')


class SMSCodeView(View):
    def get(self, request, mobile):
        # 补充逻辑,避免频繁发送短信验证码
        conn = get_redis_connection('verify_code')
        flag = conn.get('flag_%s' % mobile)
        if flag:
            return http.JsonResponse({'code': 0, 'errmsg': '频繁发送短信'})

        # 提取参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少必要参数'})

        # 校验参数
        image_code_server = conn.get('img_%s' % uuid)  # 返回的是字节类型
        # 判断数据库的数据是否过期
        if not image_code_server:
            return http.JsonResponse({'code': 400, 'errmsg': '图形验证码过期'})

        # 忽视图形验证码的大小写
        if image_code_client.lower() != image_code_server.decode().lower():
            return http.JsonResponse({'code': 400, 'errmsg': '输入图形验证码不正确'})

        # 避免频繁发送图形验证码
        conn.delete('img_%s' % uuid)

        # 随机生成6位数
        sms_code = '%06d' % random.randint(0, 999999)
        print('短信验证码: ', sms_code)

        # 创建pipeline管道优化redis
        p = conn.pipeline()
        try:
            # conn.setex('sms_%s' % mobile, 300, sms_code)
            p.setex('sms_%s' % mobile, 300, sms_code)

            # 补充逻辑,用flag标识避免频繁发送短信验证
            # conn.setex('flag_%s' % mobile, 60, '2')
            p.setex('flag_%s' % mobile, 60, '2')

            # 执行管道
            p.execute()

        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 0, 'errmsg': '数据库保存数据失败'})

        # 发送短信
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # 使用异步方案解决发送短信的耗时操作,让发送短信和响应互不影响
        # 只有使用delay()方法才是启动了异步方案
        send_sms_code.delay(mobile, sms_code)
        # 构造响应
        return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


class ImageCodeView(View):
    def get(self, request, uuid):
        # 生成图形验证码
        text, image = captcha.generate_captcha()
        print('图形验证码: ', text)
        # 保存图形验证码数据到redis中
        try:
            conn = get_redis_connection('verify_code')
            conn.setex('img_%s' % uuid, 300, text)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})

        # 响应数据,返回图形用常用对象,json对象无法返回图片
        return http.HttpResponse(image, content_type='image/jpg')
